package edu.hnui.shop.controller.admin;

import edu.hnui.shop.anotations.AdminPermission;
import edu.hnui.shop.commons.ResultCodeEnum;
import edu.hnui.shop.exception.ShopBusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/admin/admin")
public class AdminController {

    @Value("${admin.email}")
    private String email;
    @Value("${admin.password}")
    private String pwd;


    @RequestMapping(value="/index",method = RequestMethod.GET)
    @AdminPermission
    public String index(){
        return "/admin/admin/index";
    }

    @RequestMapping(value="/loginPage",method = RequestMethod.GET)
    public String loginPage(){
        return "/admin/admin/login";
    }

    @Resource
    private HttpServletRequest request;

    @RequestMapping(value="/login",method = RequestMethod.POST)
    public String login(String email,String pwd){
        //基本的字符串的格式校验
        if(!StringUtils.hasLength(email) || !StringUtils.hasLength(pwd)){
            throw new ShopBusinessException(ResultCodeEnum.PARAMETER_VALIDATION_ERROR);
        }

        if(this.email.equals(email)&&this.pwd.equals(pwd)){
            request.getSession().setAttribute("ADMIN_NAME",email);
             //如果登录成功跳转到首页（重定向）
            return "redirect:/admin/admin/index";
        }else{
            throw new ShopBusinessException(ResultCodeEnum.LOGIN_FAIL);
        }
    }

}
